<template>
  <el-cascader
    class="my-cascader"
    clearable
    v-bind="props.attrs"
    v-model="cascaderValue"
    :props="cascaderProps"
    @change="onChange"
  />
</template>
<script setup>
import { ref, computed, watch } from 'vue'
import { template } from 'lodash-es'
import { getTableList } from '@/api/basic'

const props = defineProps({
  model: {
    // form表单
    type: Object,
    default: () => ({})
  },
  configs: {
    // 级联配置列表
    // [{
    //   source: "loongair_shalves",
    //   field: "shalveId",
    //   valueField: "id",
    //   labelField: "code",
    //   conditions: {
    //     regionId: "${id}",
    //   },
    // }]
    type: Array,
    default: () => []
  },
  attrs: {
    // el-cascader配置属性
    type: Object,
    default: () => ({})
  },
  checkStrictly: {
    // 是否允许选择父节点
    type: Boolean,
    default: false
  }
})

const cascaderValue = ref([])

watch(
  () => props.configs?.map((c) => props.model?.[c.field])?.join(','),
  (val) => {
    if (cascaderValue.value.join(',') != val) {
      cascaderValue.value = props.configs?.map((c) => props.model?.[c.field]).filter((x) => !!x)
    }
  }
)

const onChange = (val) => {
  props.configs?.forEach((s, i) => {
    if (props.model[s.field] != val?.[i]) {
      // eslint-disable-next-line vue/no-mutating-props
      props.model[s.field] = val?.[i] || undefined
    }
  })
}

// 级联配置
const cascaderProps = {
  lazy: true,
  checkStrictly: props.checkStrictly,
  lazyLoad(node, resolve) {
    const {
      level,
      data: { origin }
    } = node
    // 获取配置
    const currentConfig = props.configs?.[level]
    if (!currentConfig) {
      resolve([])
      return
    }
    // 查询条件
    const conditions = Object.keys(currentConfig.conditions || {}).reduce((t, c) => {
      try {
        const val = template(currentConfig.conditions[c])({
          ...props.model,
          ...origin
        })
        t[c] = val
        return t
      } catch (e) {}
    }, {})
    // 查询数据
    getTableList({
      source: currentConfig.source,
      page: 1,
      size: 99999,
      conditions
    }).then((res) => {
      resolve(
        (res.List || []).map((item) => ({
          value: item[currentConfig.valueField || 'id'],
          label: item[currentConfig.labelField || 'code'],
          origin: item, // 保存数据
          leaf: level >= props.configs?.length - 1
        }))
      )
    })
  }
}
</script>
<style lang="less">
.my-cascader.el-cascader {
  width: 100%;
  min-width: 447px;
}
</style>
